import ctypes
import logging
import threading
import time
import tkinter as tk
from tkinter import scrolledtext


class LogWindow:
    def __init__(self, root):
        self.root = root
        self.root.title("No Lock")
        self.root.geometry("800x480")
        self.scroll_lock_status = True  # 初始 Scroll Lock 状态为 True
        self.simulate_thread = None  # 用于存储模拟线程
        self.stop_event = threading.Event()  # 用于通知线程停止的事件对象
        self.root.resizable(False, False)  # 禁止调整窗口大小

        # 创建一个 ScrolledText 作为日志视图
        self.log_view = scrolledtext.ScrolledText(root)
        self.log_view.pack(expand=True, fill='both')

        # 创建一个 Frame 来放置按钮
        button_frame = tk.Frame(root)
        button_frame.pack(side=tk.BOTTOM, fill=tk.X)

        # 创建几个按钮
        self.button1 = tk.Button(button_frame, text="Debug Log", command=self.add_debug_log)
        self.button1.pack(side=tk.LEFT, expand=True, fill=tk.X)
        self.button2 = tk.Button(button_frame, text="Info Log", command=self.add_info_log)
        self.button2.pack(side=tk.LEFT, expand=True, fill=tk.X)
        self.simulate_button = tk.Button(button_frame, text="Simulate Scroll Lock", command=self.toggle_simulate)
        self.simulate_button.pack(side=tk.LEFT, expand=True, fill=tk.X)

        # 配置日志记录器
        self.configure_logger()

    def configure_logger(self):
        # 创建一个日志记录器
        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)

        # 创建一个 StreamHandler，将日志信息输出到日志视图
        class TextWidgetHandler(logging.Handler):
            def __init__(self, widget):
                super().__init__()
                self.widget = widget

            def emit(self, record):
                msg = self.format(record)
                self.widget.configure(state='normal')
                self.widget.insert(tk.END, msg + '\n')
                self.widget.see(tk.END)  # 自动滚动到最新的日志
                self.widget.configure(state='disabled')

        handler = TextWidgetHandler(self.log_view)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(threadName)s - %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)

    def add_debug_log(self):
        logging.debug("This is a debug message from the Debug Log button")

    def add_info_log(self):
        logging.info("This is an info message from the Info Log button")

    def toggle_simulate(self):
        if self.simulate_thread is None:
            self.stop_event.clear()  # 清除停止事件
            self.simulate_thread = threading.Thread(target=self.simulate_scroll_lock)
            self.simulate_thread.daemon = True
            self.simulate_thread.start()
            self.simulate_button.config(text="Stop Simulate Scroll Lock")
        else:
            self.stop_simulate()

    def stop_simulate(self):
        if self.simulate_thread:
            self.stop_event.set()  # 设置停止事件
            self.simulate_thread = None
            self.simulate_button.config(text="Simulate Scroll Lock")

    def simulate_scroll_lock(self):
        local_data = threading.local()
        local_data.tick = 0
        local_data.count = 0

        def press_scroll_lock():
            ctypes.windll.user32.keybd_event(0x91, 0, 0, 0)  # 按下 Scroll Lock
            ctypes.windll.user32.keybd_event(0x91, 0, 2, 0)  # 释放 Scroll Lock
            time.sleep(0.5)
            ctypes.windll.user32.keybd_event(0x91, 0, 0, 0)  # 按下 Scroll Lock
            ctypes.windll.user32.keybd_event(0x91, 0, 2, 0)  # 释放 Scroll Lock
            logging.info(f"Finish Scroll Lock key press simulation [{local_data.count}].")

        while not self.stop_event.is_set():
            if local_data.tick % 12 == 0:
                press_scroll_lock()
                local_data.count += 1

            local_data.tick += 1
            time.sleep(10)

        logging.info(f"Tick Thread stopped.")


if __name__ == "__main__":
    root = tk.Tk()
    window = LogWindow(root)
    root.mainloop()
